package de.fme.publishing;

import java.util.concurrent.ExecutionException;

import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.transaction.TransactionService;

public abstract class AbstractTransactionJob{

	private String runAsUser;
	private TransactionService transactionService;

	public void execute() {

		AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>() {
			public Void doWork() {
				executeWithinTransaction();
				return null;
			}

			private void executeWithinTransaction() {
				getTransactionService().getRetryingTransactionHelper()
						.doInTransaction(
								new RetryingTransactionCallback<Object>() {
									public Object execute() throws Exception {
										try {
											doExecute();
											return null;
										} catch (Throwable t) {
											throw new Exception();
										}
									}
								});
			}
		}, getRunAsUser());
	}

	public String getRunAsUser() {
		return runAsUser;
	}

	public void setRunAsUser(String runAsUser) {
		this.runAsUser = runAsUser;
	}

	protected abstract void doExecute() throws ExecutionException;

	public TransactionService getTransactionService() {
		return transactionService;
	}

	public void setTransactionService(TransactionService transactionService) {
		this.transactionService = transactionService;
	}
}